#!/usr/bin/php
<?

/**
 * This plugin reports S3 transfer speeds, by downloading a random file from a specified bucket and path.
 *
 * The test file will be selected from TEST_PATH in TEST_BUCKET, and will not exceed MAX_FILE_SIZE.
 *
 * The plugin requires class.s3.php from this checkout:
 * svn checkout http://php-aws.googlecode.com/svn/trunk/ php-aws-read-only
 *
 * You'll need to rename it to S3.php and insert your AWS account and key.
 * 
 */
require_once("S3.php");

// Custom settings.

// The bucket name to use for testing.
define('TEST_BUCKET', 'your-bucket-name'); 

// Tests will download a random file from this path. Files must be public.
define('TEST_PATH', 'your-path');

// Test files will not exceed this size.
define('MAX_FILE_SIZE', 5 * 1000 * 1000);



// Munin configuration
if(isset($argv[1]) && $argv[1] == 'autoconf') {
    echo "yes\n";
    exit;
}

// More Munin configuration
if(isset($argv[1]) && $argv[1] == 'config') {
    echo "graph_title S3Speed\n";
    echo "graph_args --base 1000 -l 0\n";
    echo "graph_vlabel speed in kB/s\n";
    echo "graph_category network\n";
    echo "s3speed.label s3speed\n";
    echo "s3speed.draw AREA\n";
    exit;
}

// Create an s3 object
$s3 = new S3();

// Get contents of bucket & path
$contents = $s3->getBucketContents(TEST_BUCKET, TEST_PATH);

// Load valid files into array
$files = array();
foreach($contents as $file) {
    if($file['type'] == 'key' && $file['size'] <= MAX_FILE_SIZE) {
        $files[] = $file;
    }
}

// Choose a random file from the contents
$testFile = $files[array_rand($files)];
$testFileName = $testFile['name'];
$url = "http://" . TEST_BUCKET . ".s3.amazonaws.com/" . $testFileName;

// We'll be writing the downloaded file to /dev/null
$fh = fopen("/dev/null", "w");

// Download the file
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
fclose($fh);

// Find the transfer rate
$rate = curl_getinfo($ch, CURLINFO_SPEED_DOWNLOAD);
curl_close($ch);

// Output the transfer rate
$data = $rate/1000;
echo "s3speed.value $data";

?>

